package com.example.sqldemo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.blankj.utilcode.util.PathUtils;

/**
 * SQLite帮助类：打开外部DB文件
 *
 * @author XX
 * @since 2015年7月8日 11:20:28
 */
public class DBManager {
    public static SQLiteDatabase mDatabase = null;
    private static Context mContext;

    /**
     * 内存DB文件存储路径
     */
    public static String DB_PATH = "";
    public static String DB_NAME = "";
    private static int BUFFER_SIZE = 40000;

    /**
     * 单例模式：获取DBManager实例
     *
     * @param context
     * @return
     */
    public static SQLiteDatabase getInstance(Context context, String dbPath,String dbFileName) {
        mContext = context;
        DB_PATH =  dbPath;
        DB_NAME = dbFileName;
        if (mDatabase == null) {
            synchronized (DBManager.class) {
                mDatabase = openDatabase(dbFileName);
            }
        }
        return mDatabase;
    }

    public void close() {
        mDatabase.close();
        mDatabase = null;
    }

    /**
     * 获取数据库
     *
     * @return
     */
    public SQLiteDatabase getDatabase() {
        return mDatabase;
    }

    /**
     * 设置数据库
     *
     * @param db
     */
    public void setDatabase(SQLiteDatabase db) {
        mDatabase = db;
    }

    /**
     * 关闭数据库
     */
    public void closeDatabase() {
        if (mDatabase != null) {
            mDatabase.close();
        }
        mDatabase = null;
    }

    /**
     * 从本地读取DB文件 ，并加载到内存
     *
     * @return
     */
    private static SQLiteDatabase openDatabase(String dbFileName) {
        try {
            File file = new File(DB_PATH);
            if (file.exists()){
                SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH
                        + "/" + dbFileName, null);
                return db;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}